/***************************************************************************************************
  *Copyright(C),2010-2016,Sumscope
  *FileName	:  UISingleton.h
  *Author	:  scofined.qi
  *Version	:  1.0
  *Date		:  2015/01/23
  *Desc		:  模版单例UISingleton
  *Relation :  
  *Usage	:  1.继承该类，将类本身作为模板参数；2.在cpp中使用IMPL_SINGLETON来增加实现
  *Function :  
  *History	:  
***************************************************************************************************/
#pragma once

#include "../sync/lock.h"
#include "../core.h"

namespace qb {
    namespace base{

	template<class T>
    class S_CORE_EXPORT Singleton
	{
	public:
		static T *& instance()
		{
			static TSingleton_Term term;
			static CSLock lock;
			if(ms_instance == NULL)
			{
				SCOPED_LOCK(lock);
				if (ms_instance == NULL)
				{
					ms_instance = new T();
				}
			}
			return ms_instance;
		}
	protected:
		Singleton(){NULL;}
		~Singleton(){NULL;}
	private:
		static T* ms_instance;
		typedef struct _TSingleton_Term{
			~_TSingleton_Term()
			{
				if(instance() != NULL)
				{
					delete instance();
					instance() = NULL;
				}
			}
		}TSingleton_Term;
	};

	template<typename T>
	T* Singleton<T>::ms_instance = NULL;

	//#define IMPL_SINGLETON(CLASS_NAME)						
	//\
	//UILock UISingleton<CLASS_NAME>::ms_lock;				\
	//CLASS_NAME* UISingleton<CLASS_NAME>::ms_instance=NULL;	\
	//template<class CLASS_NAME>								\
	//CLASS_NAME* UISingleton<CLASS_NAME>::instance()			\
	//{														\
	//	if(NULL==ms_instance)								\
	//	{													\
	//		UIScopedLock scoped_lock(&ms_lock);				\
	//		if(NULL==ms_instance)							\
	//		{												\
	//			ms_instance = new CLASS_NAME();				\
	//		}												\
	//	}													\
	//	return (CLASS_NAME*)ms_instance;					\

    }
}
